package com.iplay.实战java高并发程序设计.chapter5.c58;

import java.util.Arrays;

/**
 * @author dangwu
 * @since 2021/11/9 3:29 下午
 */
public class ShellSort {
    public static void main(String[] args) {
        int[] arr = {9,1,5,3,6,2};
        shellSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void shellSort(int[] arr){
        //计算出最大的h值
        int h = 1;
        while (h <= arr.length /3){
            h = h*3 + 1;
        }
        while (h > 0){
            for (int i = h; i < arr.length; i++) {
                if (arr[i] < arr[i - h]){
                    int temp = arr[i];
                    int j = i - h;
                    while (j >= 0 && arr[j] > temp){
                        arr[j+h] = arr[j];
                        j -= h;
                    }
                    arr[j+h] = temp;
                }
            }
            //计算出下一个h值
            h = (h-1)/3;
        }
    }
}
